package com.example.managemyself.util;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.example.managemyself.config.AppConfig;

import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * API连接诊断工具类
 * 用于诊断和修复API连接问题
 */
public class ApiConnectionDiagnostic {
    private static final String TAG = "ApiConnectionDiagnostic";
    
    // 诊断结果回调接口
    public interface DiagnosticCallback {
        void onSuccess(String message);
        void onError(String error);
        void onProgress(String progress);
    }
    
    // 增强的HTTP客户端配置
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .followRedirects(true)
            .followSslRedirects(true)
            .build();
    
    private static final ExecutorService executor = Executors.newCachedThreadPool();
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());
    
    /**
     * 全面诊断API连接问题
     */
    public static void diagnoseApiConnection(Context context, DiagnosticCallback callback) {
        notifyProgress(callback, "🔍 开始API连接诊断...");
        
        executor.execute(() -> {
            try {
                // 步骤1: 检查网络连接
                notifyProgress(callback, "📡 检查网络连接状态...");
                if (!NetworkUtils.isNetworkAvailable(context)) {
                    notifyError(callback, "❌ 网络不可用，请检查网络连接");
                    return;
                }
                notifyProgress(callback, "✅ 网络连接正常");
                
                // 步骤2: 检查网络类型
                String networkType = NetworkUtils.getNetworkTypeDescription(context);
                notifyProgress(callback, "📶 网络类型: " + networkType);
                
                // 步骤3: 检查API配置
                notifyProgress(callback, "⚙️ 检查API配置...");
                AppConfig config = AppConfig.getInstance();
                String baseUrl = config.getApiBaseUrl();
                
                if (baseUrl == null || baseUrl.contains("your_server")) {
                    notifyError(callback, "❌ API地址配置错误: " + baseUrl + 
                        "\n请在设置中配置正确的API地址");
                    return;
                }
                notifyProgress(callback, "✅ API地址配置: " + baseUrl);
                
                // 步骤4: 测试API健康检查端点
                testApiHealthCheck(baseUrl, callback);
                
            } catch (Exception e) {
                Log.e(TAG, "诊断过程中发生异常", e);
                notifyError(callback, "❌ 诊断失败: " + e.getMessage());
            }
        });
    }
    
    /**
     * 测试API健康检查端点
     */
    private static void testApiHealthCheck(String baseUrl, DiagnosticCallback callback) {
        notifyProgress(callback, "🏥 测试API健康检查端点...");
        
        // 构建健康检查URL
        String healthCheckUrl = buildHealthCheckUrl(baseUrl);
        notifyProgress(callback, "🔗 连接地址: " + healthCheckUrl);
        
        Request request = new Request.Builder()
                .url(healthCheckUrl)
                .addHeader("Accept", "application/json")
                .addHeader("User-Agent", "ManageMyself-Android/1.0")
                .addHeader("Connection", "keep-alive")
                .build();
        
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "API健康检查失败", e);
                analyzeConnectionFailure(e, callback);
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (response.isSuccessful()) {
                        String responseBody = response.body() != null ? 
                            response.body().string() : "";
                        
                        notifyProgress(callback, "📋 服务器响应: HTTP " + response.code());
                        
                        // 尝试解析JSON响应
                        try {
                            JSONObject json = new JSONObject(responseBody);
                            boolean success = json.optBoolean("success", false);
                            String message = json.optString("message", "");
                            String version = json.optString("version", "未知");
                            
                            if (success) {
                                notifySuccess(callback, 
                                    "🎉 API连接成功！\n" +
                                    "📡 服务器状态: 正常运行\n" +
                                    "📝 响应消息: " + message + "\n" +
                                    "🔢 API版本: " + version + "\n" +
                                    "⏰ 响应时间: " + (System.currentTimeMillis() - call.request().tag(Long.class)) + "ms");
                            } else {
                                notifyError(callback, "❌ API返回错误: " + message);
                            }
                        } catch (Exception e) {
                            // JSON解析失败，但HTTP状态码成功
                            notifySuccess(callback, 
                                "✅ API连接成功！\n" +
                                "📡 HTTP状态码: " + response.code() + "\n" +
                                "📋 响应内容: " + (responseBody.length() > 100 ? 
                                    responseBody.substring(0, 100) + "..." : responseBody));
                        }
                    } else {
                        analyzeHttpError(response, callback);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "处理响应失败", e);
                    notifyError(callback, "❌ 处理服务器响应失败: " + e.getMessage());
                }
            }
        });
    }
    
    /**
     * 构建健康检查URL
     */
    private static String buildHealthCheckUrl(String baseUrl) {
        // 移除末尾的斜杠
        if (baseUrl.endsWith("/")) {
            baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
        }
        
        // 添加健康检查端点
        if (baseUrl.contains("/api")) {
            // 如果已包含/api，直接添加健康检查端点
            return baseUrl + "/health/check";
        } else {
            // 如果不包含/api，添加完整路径
            return baseUrl + "/api/health/check";
        }
    }
    
    /**
     * 分析连接失败原因
     */
    private static void analyzeConnectionFailure(IOException e, DiagnosticCallback callback) {
        String errorMsg = e.getMessage();
        if (errorMsg == null) {
            errorMsg = e.getClass().getSimpleName();
        }
        
        StringBuilder diagnosis = new StringBuilder();
        diagnosis.append("❌ API连接失败\n\n");
        diagnosis.append("🔍 错误分析:\n");
        
        if (errorMsg.contains("Connection refused") || errorMsg.contains("连接被拒绝")) {
            diagnosis.append("• 连接被拒绝 - 服务器可能未启动\n");
            diagnosis.append("• 防火墙可能阻止了连接\n");
            diagnosis.append("• 端口可能被占用或关闭\n\n");
            diagnosis.append("💡 解决建议:\n");
            diagnosis.append("1. 检查服务器是否正在运行\n");
            diagnosis.append("2. 确认防火墙设置\n");
            diagnosis.append("3. 验证端口号是否正确\n");
        } else if (errorMsg.contains("timeout") || errorMsg.contains("超时")) {
            diagnosis.append("• 连接超时 - 网络延迟过高\n");
            diagnosis.append("• 服务器响应缓慢\n\n");
            diagnosis.append("💡 解决建议:\n");
            diagnosis.append("1. 检查网络连接质量\n");
            diagnosis.append("2. 尝试更换网络环境\n");
            diagnosis.append("3. 联系服务器管理员\n");
        } else if (errorMsg.contains("UnknownHostException") || errorMsg.contains("unknown host")) {
            diagnosis.append("• 无法解析服务器地址\n");
            diagnosis.append("• DNS解析失败\n\n");
            diagnosis.append("💡 解决建议:\n");
            diagnosis.append("1. 检查API地址是否正确\n");
            diagnosis.append("2. 确认DNS设置\n");
            diagnosis.append("3. 尝试使用IP地址替代域名\n");
        } else if (errorMsg.contains("Network is unreachable") || errorMsg.contains("网络不可达")) {
            diagnosis.append("• 网络不可达\n");
            diagnosis.append("• 路由配置问题\n\n");
            diagnosis.append("💡 解决建议:\n");
            diagnosis.append("1. 检查网络连接\n");
            diagnosis.append("2. 重启网络设备\n");
            diagnosis.append("3. 联系网络管理员\n");
        } else {
            diagnosis.append("• 未知网络错误: ").append(errorMsg).append("\n\n");
            diagnosis.append("💡 解决建议:\n");
            diagnosis.append("1. 检查网络连接\n");
            diagnosis.append("2. 重启应用\n");
            diagnosis.append("3. 联系技术支持\n");
        }
        
        notifyError(callback, diagnosis.toString());
    }
    
    /**
     * 分析HTTP错误
     */
    private static void analyzeHttpError(Response response, DiagnosticCallback callback) {
        int code = response.code();
        String message = response.message();
        
        StringBuilder diagnosis = new StringBuilder();
        diagnosis.append("❌ API服务器错误\n\n");
        diagnosis.append("📋 HTTP状态码: ").append(code).append(" ").append(message).append("\n\n");
        diagnosis.append("🔍 错误分析:\n");
        
        switch (code) {
            case 404:
                diagnosis.append("• 404 Not Found - API端点不存在\n");
                diagnosis.append("• 可能是API路径配置错误\n\n");
                diagnosis.append("💡 解决建议:\n");
                diagnosis.append("1. 检查API地址配置\n");
                diagnosis.append("2. 确认服务器API端点\n");
                diagnosis.append("3. 联系后端开发人员\n");
                break;
            case 500:
                diagnosis.append("• 500 Internal Server Error - 服务器内部错误\n");
                diagnosis.append("• 后端服务出现异常\n\n");
                diagnosis.append("💡 解决建议:\n");
                diagnosis.append("1. 联系服务器管理员\n");
                diagnosis.append("2. 检查服务器日志\n");
                diagnosis.append("3. 稍后重试\n");
                break;
            case 403:
                diagnosis.append("• 403 Forbidden - 访问被禁止\n");
                diagnosis.append("• 可能缺少认证信息\n\n");
                diagnosis.append("💡 解决建议:\n");
                diagnosis.append("1. 检查API密钥配置\n");
                diagnosis.append("2. 确认访问权限\n");
                diagnosis.append("3. 联系管理员\n");
                break;
            default:
                diagnosis.append("• HTTP错误码: ").append(code).append("\n");
                diagnosis.append("• 服务器返回错误响应\n\n");
                diagnosis.append("💡 解决建议:\n");
                diagnosis.append("1. 检查服务器状态\n");
                diagnosis.append("2. 查看服务器文档\n");
                diagnosis.append("3. 联系技术支持\n");
                break;
        }
        
        notifyError(callback, diagnosis.toString());
    }
    
    /**
     * 快速修复API连接问题
     */
    public static void quickFixApiConnection(Context context, DiagnosticCallback callback) {
        notifyProgress(callback, "🔧 开始快速修复...");
        
        executor.execute(() -> {
            try {
                // 1. 更新API配置为当前IP
                AppConfig config = AppConfig.getInstance();
                String currentIp = "10.163.78.16"; // 您当前的IP
                String newApiUrl = "http://" + currentIp + ":8080/api";
                
                config.setString(AppConfig.API_BASE_URL, newApiUrl);
                notifyProgress(callback, "✅ 已更新API地址为: " + newApiUrl);
                
                // 2. 测试新的API地址
                testApiHealthCheck(newApiUrl, new DiagnosticCallback() {
                    @Override
                    public void onSuccess(String message) {
                        notifySuccess(callback, "🎉 快速修复成功！\n" + message);
                    }
                    
                    @Override
                    public void onError(String error) {
                        notifyError(callback, "❌ 快速修复失败，需要手动配置\n" + error);
                    }
                    
                    @Override
                    public void onProgress(String progress) {
                        notifyProgress(callback, progress);
                    }
                });
                
            } catch (Exception e) {
                Log.e(TAG, "快速修复失败", e);
                notifyError(callback, "❌ 快速修复失败: " + e.getMessage());
            }
        });
    }
    
    // 辅助方法
    private static void notifySuccess(DiagnosticCallback callback, String message) {
        if (callback != null) {
            mainHandler.post(() -> callback.onSuccess(message));
        }
    }
    
    private static void notifyError(DiagnosticCallback callback, String error) {
        if (callback != null) {
            mainHandler.post(() -> callback.onError(error));
        }
    }
    
    private static void notifyProgress(DiagnosticCallback callback, String progress) {
        if (callback != null) {
            mainHandler.post(() -> callback.onProgress(progress));
        }
    }
} 